package com.hjxr.quota.datasource.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.hjxr.quota.datasource.domain.ColnameAlias;
import com.hjxr.quota.datasource.domain.TablenameAlias;
import com.hjxr.quota.datasource.service.ColnameAliasService;
import com.hjxr.quota.datasource.service.DatasourceQueryService;
import com.hjxr.quota.datasource.service.TablenameAliasService;
import com.hjxr.quota.tool.database.ColumnInfo;
import com.hjxr.sysadmin.web.domain.TreeSelect;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.util.*;

/**
 * 字段别名控制器层
 *
 * @author sun
 * @version v1.0
 * @since 2020-08-16
 */
@RestController
@RequestMapping("/colAlias")
@Api(tags = "字段别名接口")
public class ColnameAliasController extends ApiController {

  @Autowired
  private ColnameAliasService colnameAliasService;
  @Autowired
  private DatasourceQueryService datasourceQueryService;
  @Autowired
  private TablenameAliasService tablenameAliasService;

  /**
   * 转向到页面
   *
   * @return 页面地址
   */
  @GetMapping(value = "/{orgId}/{funcId}")
  @ApiOperation("前台页面返回")
  private ModelAndView gotoFunc() {
    return new ModelAndView("quota/colAlias/colAlias");
  }

  @GetMapping(value = "/tableTree")
  private ModelAndView goTableTree() {
    return new ModelAndView("quota/tableTree/tableTree");
  }

  /**
   * 分页查询所有数据
   *
   * @return 所有数据
   */
  @GetMapping
  @ApiOperation("分页查询所有数据")
  @ApiImplicitParams(
          {@ApiImplicitParam(paramType = "query", dataType = "String", name = "current", value = "当前页", defaultValue = "1", required = true),
                  @ApiImplicitParam(paramType = "query", dataType = "String", name = "size", value = "一页大小", defaultValue = "10", required = true),
                  @ApiImplicitParam(paramType = "query", dataType = "Boolean", name = "ifCount", value = "是否查询总数", defaultValue = "true"),
                  @ApiImplicitParam(paramType = "query", dataType = "String", name = "ascs", value = "升序字段，多个用逗号分隔"),
                  @ApiImplicitParam(paramType = "query", dataType = "String", name = "descs", value = "降序字段，多个用逗号分隔")
          })
  public R<IPage<ColnameAlias>> selectAll() {
    BaseForm form = new BaseForm();
    QueryWrapper<ColnameAlias> query = (QueryWrapper<ColnameAlias>) form.pageQueryWrapperCustom(form.getParameters(), new QueryWrapper<ColnameAlias>());
    return success(colnameAliasService.page(form.getPlusPagingQueryEntity(), query));
  }


  @GetMapping("/byTable")
  @ApiOperation("根据数据表别名ID获取字段别名记录")
  private R<List<ColnameAlias>> selectByTablenameAliasId(@RequestParam(required = true) Integer tablenameAliasId) {
    return success(colnameAliasService.selectByTablenameAliasId(tablenameAliasId));
  }

  @GetMapping("{id}")
  @ApiOperation("通过主键查询单条数据")
  public R<ColnameAlias> selectOn(@PathVariable Serializable id) {
    return success(this.colnameAliasService.getById(id));
  }

  @ApiOperation("新增数据")
  @PostMapping("/addNew")
  public R<Boolean> insert(@RequestBody ColnameAlias entity) {
    return success(this.colnameAliasService.save(entity));
  }

  @PutMapping
  @ApiOperation("修改数据")
  public R<Boolean> update(@RequestBody ColnameAlias entity) {
    return success(this.colnameAliasService.update(entity));
  }

  @PostMapping("/delete")
  @ApiOperation("删除数据")
  public R<Boolean> delete(@RequestBody HashMap<String, List<Long>> params) {
    return success(this.colnameAliasService.removeByIds(params.get("idList")));
  }

  @ApiOperation("同步数据表字段到别名表")
  @PostMapping("/syncColumns")
  public R<Boolean> syncColumn(@RequestBody TablenameAlias tablenameAlias) {
    try {
      List<ColumnInfo> list = datasourceQueryService.getFullColumns(tablenameAlias.getDatasourceId(), tablenameAlias.getTableName());
      for (ColumnInfo column : list) {
        if (colnameAliasService.selectByColumnName(tablenameAlias.getId(), column.getName()) != null)
          continue;
        ColnameAlias entity = new ColnameAlias();
        String alias = column.getComment();
        alias = alias == null ? "" : alias;
        entity.setColumnAlias(alias);
        entity.setColumnDesc(alias);
        entity.setDataType(column.getType());
        entity.setColumnName(column.getName());
        entity.setIsdimension("0");
        entity.setIsquota("0");
        entity.setTablenameAliasId(tablenameAlias.getId());
        entity.setUpdateDate(new Date());
        entity.setUpdateBy(tablenameAlias.getUpdateBy());
        colnameAliasService.save(entity);
      }
    } catch (IOException e) {
      return failed(e.getMessage());
    }
    return success(true);
  }

  @PostMapping("/batchUpdate")
  @ApiOperation("批量更新数据")
  public R<Boolean> batchUpdate(@RequestBody List<ColnameAlias> list) {
    int i = 0;
    for (ColnameAlias t : list) {
      colnameAliasService.update(t);
    }
    return success(true);
  }

  /**
   * 获取表结构树
   */
  @GetMapping("/treeSelect")
  @ApiOperation("获取表结构树")
  public R<List<TreeSelect>> treeSelect(@RequestParam(required = true) Integer datasourceId)
  {
    List<TablenameAlias> tables = tablenameAliasService.selectEnableByDatasourceId(datasourceId);

    List<TreeSelect> tree = new ArrayList<>();
    for (TablenameAlias table: tables){
      TreeSelect ts = new TreeSelect();
      ts.setId((long)table.getId());
      String label = "".equals(table.getTableNameAlias()) || table.getTableNameAlias() == null ? table.getTableName() :
              table.getTableNameAlias();
      ts.setLabel(label);
      List<ColnameAlias> columns = colnameAliasService.selectByTablenameAliasId(table.getId());
      List<TreeSelect> nodes = new ArrayList<>();
      for (ColnameAlias column : columns){
        TreeSelect c_ts = new TreeSelect();
        c_ts.setId((long) column.getId());
        String c_label = "".equals(column.getColumnAlias()) || column.getColumnAlias() == null ? column.getColumnName() :
                column.getColumnAlias();
        c_ts.setLabel(c_label);
        nodes.add(c_ts);
      }
      ts.setChildren(nodes);
      tree.add(ts);
    }

    return success(tree);
  }

}
